package servlet;

import modle.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "UserRegisterServlet", value = "/user_register")
public class UserRegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        User user = new User();
        Map<String, String[]> parameterMap = request.getParameterMap();
        try {
            BeanUtils.copyProperties(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserService userService = new UserService();
        if (userService.register(user)){
            request.setAttribute("msg","注册成功,请登录！");
            request.getRequestDispatcher("user_login.jsp").forward(request,response);
        }else {
            request.setAttribute("msg","用户名或邮箱存在，请重新填写！");
            request.getRequestDispatcher("user_register.jsp").forward(request,response);
        }
    }
}
